<template>
  <div class="messageCenter">
    <el-tooltip
      effect="dark"
      content="通知"
      v-model:visible="showNoticeTips"
      placement="bottom">
      <span class="notice-tips">通知</span>
    </el-tooltip>
    <el-popover
      :width="860"
      :visible="popoverVisible"
      popper-style="border-radius: 8px;box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 0 8px 8px 8px;box-sizing: border-box;">
      <template #reference>
        <div class="ref-icon" @mouseenter="showNoticeTips=true" @mouseleave="showNoticeTips=false"> <el-icon v-if="!readingLen" style='font-weight: 600;' color="#4e5959" @click="handleClickPopover" :size="18"><Bell /></el-icon>
        <el-badge v-if="readingLen" class="item badge" :value="readingLen" :max="99">
          <el-icon style='font-weight: 600;' color="#4e5959" @click="handleClickPopover"><Bell /></el-icon>
        </el-badge></div>
      </template>
      <template #default>
        <div class="messageCenter-conent">
          <div class="messageCenter-conent-top">
            <div class="title-box">
              <span>消息通知</span>
              <el-tooltip content="全部已读" effect="dark" placement="right">
                <span class="iconfont icon-a-qingchuquanbuyidu icon-clear" title="" @click="handleClickAllReader"></span>
              </el-tooltip>
            </div>
            <!-- <el-button type="primary" link @click="handleClickAllReader">全部已读</el-button> -->
            <el-icon :size="20" @click="handleClickPopover"><CloseBold /></el-icon>
          </div>
          <div class="messageCenter-conent-divider">
            <el-divider style="margin: 0;" />
          </div>
          <div class="messageCenter-conent-middle">
            <!-- el-dropdown下拉菜单 -->
            <!-- <el-dropdown trigger="click" @command="handleCommand">
              <span class="el-dropdown-link">
                {{ currentType == 'all' ? '全部' : (currentType == 'activity_expire' ? '活动到期' : '库存不足') }}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="all">全部</el-dropdown-item>
                  <el-dropdown-item command="activity_expire">活动到期</el-dropdown-item>
                  <el-dropdown-item command="stock_defect">库存不足</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown> -->
            <div class="messageCenter-conent-middle-content">
              <ul class="messageCenter-conent-middle-left">
                <li class="left-item" :class="{'left-item-active':currentType==key}"  v-for="(item,key) in messgaeTypeList"   @click="changeType(key)"><div class="type-item">{{ item }}</div> <span class="red-dot" v-if="messageTypeUnread?.[key]">{{ messageTypeUnread[key]}}</span></li>
              </ul>
            <!-- listBox消息列表 -->
              <div class="listBox" v-loading="loading" >
                <template v-if="pastRecordsData.length">
                  <div class="listBox-items" v-for="(item, index) in pastRecordsData" :key="index" :class="{'isReading': item.reading === 1 }">
                    <div class="item-left">
                      <span :class="{dot:item.reading === 0}" ></span>
                    </div>
                    <div class="item-right">
                      <div class="item-top">
                        <div class="item-top-content">{{ item.content }}</div>
                      </div>
                      <div class="item-bottom">
                        <div class="item-bottom-left">
                          <div class="item-bottom-left-btn" @click="toView(item)">立即查看<span style="margin-left: 2px;">&gt;</span></div>
                          <div class="hover-box"  v-if="item.reading === 0" @mouseenter="item.showReadBtn=true"  @mouseleave="item.showReadBtn=false">
                            <div class="item-bottom-left-btn read-btn" v-show="item.showReadBtn" @click="merchantMessageChangeStatusApi([item.id])">标记为已读
                            </div>
                          </div>
                        </div>
                        <div class="item-bottom-right"><span>{{ new Date(item.createTime).format("yyyy-MM-dd hh:mm:ss") }}</span></div>
                      </div>
                    </div>
                  
                    <!-- <div class="left"></div>
                    <div class="right">
                      <p class="top">
                        {{ item.content }}
                      </p>
                      <p class="bottom">
                        {{ new Date(item.createTime).format("yyyy-MM-dd") }}
                      </p>
                    </div> -->
                  </div>
                </template>
                <div class="empty-text" v-if="!pastRecordsData.length">暂无通知</div>
              </div>
              
            </div>
          </div>
          <div  class="page">
      <el-pagination v-model:currentPage="pager.currentPage" v-model:pageSize="pager.showCount"
        :page-sizes="pager.pageSizes" background layout="total, sizes, prev, pager, next, jumper"
        :total="pager.totalResult" @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </div>
          <!-- <div class="messageCenter-conent-bottom">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="消息历史"
              placement="bottom-start">
              <el-icon :size="24" @click="handleClickGoPastRecords"><Clock /></el-icon>
            </el-tooltip>
          </div> -->
        </div>
      </template>
    </el-popover>

    <!-- 消息推送弹窗 -->
    <NoticeModal v-if="$store.state.notice.noticeList.length" @close="closeNotice" @to-link="toLink"/>
  </div>
</template>
<script setup>
import { useMenu } from "@/compositions/main/useMenu";
import { useWebSocket } from "@/compositions/notice/useWebSocket";
const {clearNotice,clearNoticeItem}=useWebSocket()
const instance=ref()
const {toRoute}=useMenu()
const router = useRouter()
const route=useRoute()
const store = useStore();
//1.需要删除消息，2不需要
const toLink=({item,index,type=1})=>{
  if(item){
    const data=item
    const toLinkPath={
      MALL:'/mall/product/list',//商城商品列表
      ACTIVITY:'/activity/list/prize',//活动商品管理
      MEMBER:'/merchant/vip_center/benefits'//会员权益
    }
    const businessType=(item.businessType+'').toUpperCase()

    const currentService=businessType=='MEMBER'?'MERCHANT':businessType
    //正处于当前页面不跳转
    if(route.path.indexOf(toLinkPath[businessType])>-1){
      return
    }
    // 激活左侧菜单
    if(store.state.user.currentService!=currentService){
      toRoute(currentService)
    }
    const info=data.businessBean?JSON.parse(data.businessBean):null
    //存储跳转参数
    if(businessType=='MALL'){
      store.commit("pointsMall/updateGoodsIds", [data?.goodsId]);
    }else if(businessType=='MEMBER'){
      store.commit("memberStore/setGoodsIds", [data?.goodsId]);
    }

    if(info){
        //商城
      if(businessType=='MALL'){
        info.id=item.businessId
        store.commit("pointsMall/updateMallConfig", info);
        store.commit("SETBOOKLIST", {
          path: "/mall/product/list",
          service: store.state.user.currentService
        });
        router.push({
          name:"MallProductList",
          params:{
            goodsName:data?.goodsName
          }
        });
      }else if(businessType=='ACTIVITY'){
        //活动
        info.actId=item.businessId 
        if(info.id){ 
          router.push({name: "ActivityPrize", params:{id:info.id}});
        }else{
          console.log('奖池id缺失')
        }
      }else if(businessType=='MEMBER'){
        //会员
        router.push({
          name:'Benefits',
          params:{
            goodsName:data?.goodsName
          }
        });
      }
      type==1&&clearNoticeItem(index)
    }
  }
}
const closeNotice=()=>{
  clearNotice()
}

//立即查看
const toView=(item)=>{
  if(item.dataJson){
    const data=JSON.parse(item.dataJson)
    data&&toLink({item:data,type:2})
    // 置为已读
    instance.value.ctx.merchantMessageChangeStatusApi([item.id])
    instance.value.data.popoverVisible=false
  }else{
    console.log('dataJson 缺失')
  }
 
}

onMounted(()=>{
  instance.value=getCurrentInstance()
})
</script>
<script>

import { merchantMessageCenterList, merchantMessageChangeStatus,messageCenterUnreadNum,messageCenterReadAll } from '@/api/messageCenter/index.js';
import NoticeModal from './NoticeModal.vue';
import {messageType} from "@/config/dictionary"
export default {
  name: 'MessageCenter',
  data() {
    return {
      showNoticeTips:false,
      currentType: 'all',
      popoverVisible: false,
      loading: false,
      pastRecordsData: [],
      isDot: false,
      readingLen:0,//未读消息数量
      pager: {
        currentPage: 1,
        showCount: 10,
        pageSizes: [10, 20, 40],
        totalResult: 0,
      },
      messgaeTypeList:messageType,
      messageTypeUnread:{}
    }
  },
  components:{
    NoticeModal
  },
  mounted() {
    this.merchantMessageCenterListApi();
    this.getAllUnread()
  },

  methods: {
    //获取所以类型消息未读状况
    getAllUnread(){
      Object.keys(this.messgaeTypeList).forEach(key=>{
        this.getUnReadMsgNum(key)
      })
    },

    async getUnReadMsgNum(type){
      const res=await messageCenterUnreadNum({
        pressType: type,
        currentPage: this.pager.currentPage,
        showCount: 200
      })
      if(res.code==200){
        if(type=='all'){
          this.readingLen=res.payload?.number??0
        }
        
        this.messageTypeUnread[type]=res.payload?.number??0
      }
    },
    //切换消息类型
    changeType(type){
      this.currentType=type
      this.pager.currentPage=1
      this.getAllUnread()
      this.merchantMessageCenterListApi()
    },

    // 下拉选择
    handleCommand(val) {
      this.currentType = val;
      this.merchantMessageCenterListApi();
    },
    // 点击打开关闭popover
    handleClickPopover() {
      this.popoverVisible = !this.popoverVisible;
    },
    // 全部已读
    async  handleClickAllReader() {
      const res=await messageCenterReadAll({})
      if(res.code==200){
        this.getAllUnread()
        this.merchantMessageCenterListApi();
      }
      // let arr = [];
      // this.pastRecordsData.forEach(item => {
      //   // 已读/未读  1/0
      //   if(item.reading === 0) {
      //     arr.push(item.id)
      //   }
      // })
      // this.merchantMessageChangeStatusApi(arr);
    },
    // 修改消息状态
    async merchantMessageChangeStatusApi(ids) {
      let res = await merchantMessageChangeStatus({
        ids
      })
      if(res.code === 200) {
        this.getAllUnread()
        this.merchantMessageCenterListApi();
      }
    },
    // 获取消息列表Api
    async merchantMessageCenterListApi() {
      this.loading = true;
      let res = await merchantMessageCenterList({
        pressType: this.currentType,
        currentPage: this.pager.currentPage,
        showCount: this.pager.showCount
      })
      if(res.code === 200) {
        this.pastRecordsData = res.payload;
        let i=0;
        (this.pastRecordsData||[]).forEach(item=>{
          item.showReadBtn=false
          
        })
        this.pager.totalResult=res.page.totalResult

        // 判断是否有未读消息
//         this.pastRecordsData.forEach(item => {
//           // 已读/未读  1/0
//           if(item.reading==0){
// // this.messageTypeUnread[this.currentType]
//           }
//           // if(item.reading === 0) {
//           //   arr.push(item.id)
//           // }
//         })
        // if(arr.length === 0) {
        //   this.isDot = false;
        // } else {
        //   this.isDot = true;
        // }
      }
      this.loading = false;
    },
    // 跳转消息历史list
    handleClickGoPastRecords() {
      this.$router.push('/messageCenter/pastRecords');
    },
    handleSizeChange(val){
      this.pager.showCount=val
      this.merchantMessageCenterListApi()
    },
    handleCurrentChange(val){
      this.pager.currentPage=val
      this.merchantMessageCenterListApi()
    }
  },
  computed:{
  }
}
</script>

<style lang="scss" scoped>
.messageCenter {
  position: relative;
  // width: 16px;
  // height: 16px;
  :deep(.el-icon) {
    cursor: pointer;
  }
}
.badge{
  // width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content:center;
  &:hover{
    background: #F3F3F3;
  }
  
  :deep(.el-icon) {
    font-size: 22px;
  }
}
.messageCenter-conent {
  &-top {
    width: 100%;
    height: 64px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title-box{
      margin-left: 14px;
      font-size: 16px;
      color: #333;
      font-weight: 700;
      .icon-clear{
        margin-left: 24px;
        color: #999;
        font-weight: 400;
        font-size: 14px;
        cursor: pointer;
      }
    }
    .el-button {
      margin-left: 16px;
    }
    .el-icon {
      margin-right: 16px;
      cursor: pointer;
    }
  }
  &-divider {
    padding: 0 16px;
  }
  &-middle {
    width: 100%;
    height: 66vh;
    display: flex;
    .messageCenter-conent-middle-content{
      height: 100%;
      display: flex;
      flex-shrink: 0;
      // align-items: flex-start;
    }

    :deep(.el-dropdown) {
      width: 100%;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      cursor: pointer;
      .el-dropdown-link {
        font-weight: 900;
        margin-left: 16px;
      }
    }
    &-left{
      width: 160px;
      padding-left: 14px;
      list-style: none;
      box-sizing: border-box;
    .left-item{
      position: relative;
      color: #666;
      padding: 20px 0;
      padding-left: 16px;
      border-bottom: 1px solid #ededed;
      border-right: 2px solid transparent;
      cursor: pointer;
      .type-item{
        position: absolute;
        top: 9px;
        left: 0;
        bottom: 0;
        width: 120px;
        text-align: center;
      }
      .red-dot{
        position: absolute;
        top: 50%;
        right: 4px;
        transform: translateY(-50%);
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 6px;
        height: 20px;
        background-color: #f00;
        color: #fff;
        border-radius: 10px;
      }
    }
    .left-item-active{
      border-right-color: #0052D9;
      color: #0052D9;
      background-color: #E8F2FF;
    }
  }
    .listBox {
      overflow-y: auto;
      width: 666px;
      box-sizing: border-box;
      border-left: 1px solid #ededed;
      &-items {
        width: 100%;
        padding: 8px;
        padding-bottom: 0;
        display: flex;
        flex-shrink: 0;
        justify-content: flex-start;
        align-items: flex-start;
        // cursor: pointer;
        // margin-bottom: 8px;
        box-sizing: border-box;
        .item-left{
          margin-top: 8px;
          width: 20px;
          display: flex;
          justify-content: flex-end;
          .dot{
            display: flex;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background-color: #f00;
          }
        }
        .item-right{
          width: 608px;
          display: flex;
          flex-direction: column;
          flex-shrink: 0;
          justify-content: flex-start;
          padding-bottom: 12px;
          margin-left: 8px;
          border-bottom: 1px solid #ededed;
          box-sizing: border-box;
        }
        .item-top{
          width: 100%;
          font-size: 14px;
          &-content{
            // white-space: nowrap;
            // overflow: hidden;
            // text-overflow: ellipsis;
          }
        }
        .item-bottom{
          margin-top: 12px;
          display: flex;
          justify-content: space-between;
          &-left{
            display: flex;
            &-btn{
              padding: 2px 4px;
              color: #0052D9;
              cursor: pointer;
              border: 1px solid;
              border-radius: 4px;
              opacity: 1;
            }
            .hover-box{
              display: flex;
              justify-content: flex-end;
              width: 96px;
            }
            .read-btn{
              // margin-left: 8px;
              color: #666;
            }
          }
        }
        &:last-child {
          margin-bottom: 0;
        }
        .left {
          width: 36px;
          height: 36px;
          background: url('') center no-repeat;
          box-sizing: border-box;
          border-radius: 40px;
          background-color: #ebf2ff;
          background-size: 24px;
        }
        .right {
          flex: 1;
          .top {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-bottom: 2px;
            font-family: PingFang SC;
            font-size: 14px;
          }
          .bottom {
            font-family: PingFang SC;
            font-size: 14px;
          }
        }
        &:hover {
          background: rgb(239, 239, 245);
          border-radius: 4px;
        }
      }
      .isReading {
        opacity: 0.6;
      }
    }
  }
  &-bottom {
    width: 100%;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    :deep(.el-icon) {
      margin-right: 16px;
      cursor: pointer;
    }
  }
}
.ref-icon{
  display: flex;
  align-items: center;
  justify-content: center;
}
.empty-text{
  margin-top: 20vh;
  text-align: center;
}
.notice-tips{
  position: absolute;
  left: 1px;
  right: 1px;
  top: 0;
  bottom: 0;
  font-size: 0;
  z-index: 0;
}
</style>